import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col} from 'antd';
import {FORM_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {partShipmentStatus, declarePlace, declareType} from '../Enum';
import TextInput from 'Shared/components/TextInput';
import DateRangePicker from 'Shared/components/DateRangePicker';
import WrappedSelect from '../common/WrappedSelect';
import SearchSelect from 'Shared/components/SearchSelect';
import DealerSelectPanel from './DealerSelectPanel';
import {hasPermissions} from './utils';
import {injectIntl, language} from './intl';
import routes from './routes';
import {getDealersQuickly} from './api';
const FormItem = Form.Item;

const declareTypeList = declareType.toList(language);
const declarePlaceList = declarePlace.toList(language);
const partShipmentStatusList = partShipmentStatus.toList(language);
class QueryPanel extends React.PureComponent {
    state = {
        data: {},
        showDealerSelectPanel: false,
    }

    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    dealerLabelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `(${d.code}) ${d.name}`;
        return '';
    }
    onSearchDealer = value =>
        getDealersQuickly({filter: value})
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            })
    onSelectDealer = data => {
        this.props.onConditionsChange('dealerId', data.id);
        this.props.onQueryDealerChange({
            id: data.id,
            code: data.code,
            name: data.name,
        });
        this.setState({
            showDealerSelectPanel: false
        });
    }
    onClickSearchDealerBtn = () => {
        this.setState({showDealerSelectPanel: true});
    }
    onCloseDealerSelectPanel = () => {
        this.setState({showDealerSelectPanel: false});
    }
    render() {
        const operations = [];
        const {data} = this.state;
        const dealerInfo = this.props.conditions.dealerId ? {
            id: this.props.queryDealer.id,
            code: this.props.queryDealer.code,
            name: this.props.queryDealer.name
        } : null;
        if(hasPermissions(this.props.permissions, PERMISSION.import))
            operations.push(<Button key="import" href={`#${routes.import.url()}`}>{this.props.intl.formatMessage({
                id: 'queryPanel.operation.import',
                defaultMessage: '导入'
            })}</Button>);
        return (
            <Form className="form-standard">
                <Row>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.partContractInvoiceCode',
                                defaultMessage: '发票号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="partContractInvoiceCode"
                                value={this.props.conditions.partContractInvoiceCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.dealer',
                                defaultMessage: '总代'
                            })}
                            {...FORM_OPTIONS.item} >
                            <SearchSelect
                                allowClear
                                value={dealerInfo}
                                placeholder={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.pleaseQuery',
                                    defaultMessage: '请输入查询'
                                })}
                                onSelect={this.onSelectDealer}
                                onSearch={this.onSearchDealer}
                                keyIndex="id"
                                labelMap={this.dealerLabelMap}
                                onClickSearchBtn={this.onClickSearchDealerBtn} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.brandId',
                                defaultMessage: '品牌'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="brandId"
                                value={this.props.conditions.brandId}
                                options={this.props.initEnum.brands}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.partShipmentStatus',
                                defaultMessage: '状态'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="partShipmentStatus"
                                value={this.props.conditions.partShipmentStatus}
                                options={partShipmentStatusList.filter(d => d.value !== -1)}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.declarePlace',
                                defaultMessage: '报关地点'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="declarePlace"
                                value={this.props.conditions.declarePlace}
                                options={declarePlaceList}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.declareType',
                                defaultMessage: '报关类型'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="declareType"
                                value={this.props.conditions.declareType}
                                options={declareTypeList}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.invoicedDate',
                                defaultMessage: '开票日期'
                            })}
                            {...FORM_OPTIONS.item}>
                            <DateRangePicker name="invoicedDate" value={this.props.conditions.invoicedDate}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.expectDepartedDate',
                                defaultMessage: '预计离港日期'
                            })}
                            {...FORM_OPTIONS.item}>
                            <DateRangePicker name="expectDepartedDate" value={this.props.conditions.expectDepartedDate}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.props.onResetClick}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.btn.reset',
                                defaultMessage: '重置'
                            })}
                        </Button>
                    </Col>
                    <Col span={18} className="col-align-right">
                        {operations}
                    </Col>
                </Row>
                {
                    this.state.showDealerSelectPanel &&
                    <DealerSelectPanel
                        selectKey={data.dealerId}
                        onCancel={this.onCloseDealerSelectPanel}
                        onSelect={this.onSelectDealer} />
                }
            </Form>
        );
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    initEnum: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onQueryDealerChange: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    intl: PropTypes.object,
    queryDealer: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    resetQueryPanel,
    querySearch,
    saveQueryDealer
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);

const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getQueryDealer = selectorFactory(['page', 'appState', 'queryDealer']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    loading: state.getIn((['page', 'domainData', 'list', 'isFetching'])),
    initEnum: getInitData(state),
    conditions: getConditions(state),
    queryDealer: getQueryDealer(state),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onQueryDealerChange: data => dispatch(saveQueryDealer(data)),
    querySearch: () => dispatch(querySearch()),
    onResetClick: () => dispatch(resetQueryPanel()),
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
